package com.jspxcms.plug.service.impl;

import com.jspxcms.plug.domain.Resume;
import com.jspxcms.plug.domain.UserFavorite;
import com.jspxcms.plug.repository.UserFavoriteDao;
import com.jspxcms.plug.service.UserFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.List;

/**
 * Created by yuanyue on 14-9-21.
 */
@Service
@Transactional(readOnly = true)
public class UserFavoriteServiceImpl implements UserFavoriteService {
    @Override
    public UserFavorite save(UserFavorite favorite) {
        return userFavoriteDao.save(favorite);
    }

    @Override
    public boolean exists(Integer userId, Integer id) {
        List<UserFavorite> byUserIdAndNewsId = userFavoriteDao.findByUserIdAndNewsId(userId, id);
        return byUserIdAndNewsId != null && byUserIdAndNewsId.size() > 0;
    }

    @Override
    public boolean delete(Integer userId, Integer id) {
        return userFavoriteDao.delete(userId, id) > 0;
    }

    @Override
    public Page<UserFavorite> findByUserId(final Integer userId, final Integer type, Integer pageIndex, Integer pageSize) {
        Specification<UserFavorite> spec = new Specification<UserFavorite>() {
            @Override
            public Predicate toPredicate(Root<UserFavorite> userFavoriteRoot, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //userFavoriteRoot = criteriaQuery.from(UserFavorite.class);
                Path pathUserId = userFavoriteRoot.get("userId");
                Path pathType = userFavoriteRoot.get("typeId");
                return criteriaBuilder.and(
                        criteriaBuilder.equal(pathUserId, userId),
                        criteriaBuilder.equal(pathType, type)
                );
            }
        };
        Pageable page = new PageRequest(pageIndex, pageSize);
        return userFavoriteDao.findAll(spec, page);
    }

    @Autowired
    private UserFavoriteDao userFavoriteDao;
}
